#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright 2020 Huawei Technologies Co., Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import sys
import time
import acl
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED, ALL_COMPLETED
from common.const import DEBUG, INFO, WARNING, ERROR
from common.log import Log, check_ret
sys.path.append("..")


class ThreadPoolInfo():
    def __init__(self):
        self.class_name = self.__class__.__name__
        self.pool = None
        self.task_list = []

    def update_thread_pool_info(self, task):
        self.task_list.append(task)


class ThreadPool():
    def __init__(self):
        self.class_name = self.__class__.__name__
        self.host_thread_pool_info = ThreadPoolInfo()

    def host_thread_pool(self, thread_num):
        if thread_num <= 0:
            Log.do_log(ERROR, self.class_name, 'host_thread_pool', 'thread_num must be larger than 0')
            return 1
        self.host_thread_pool_info.pool = ThreadPoolExecutor(max_workers=thread_num)
        if self.host_thread_pool_info.pool is None:
            Log.do_log(ERROR, self.class_name, 'host_thread_pool', 'fail to create thread pool')
            return 2
        return 0

    def combined_function_to_host_thread(self, func, func_args: list):
        task = self.host_thread_pool_info.pool.submit(func, *func_args)
        if task is None:
            Log.do_log(ERROR, self.class_name, func.__name__, 'fail to submit func to pool')
            return 1
        self.host_thread_pool_info.update_thread_pool_info(task)
        return 0

    def wait_host_thread(self, task_list, timeout=None, return_when=ALL_COMPLETED):
        wait(task_list, timeout, return_when)

    def destroy_host_thread(self):
        if self.host_thread_pool_info.pool is not None:
            self.host_thread_pool_info.pool.shutdown(wait=True)
        self.host_pool_reset()

    def host_pool_reset(self):
        self.host_thread_pool_info.pool = None
        self.host_thread_pool_info.task_list.clear()

    def  __del__(self):
        self.destroy_host_thread()

